layui.config({
    base: 'assets/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index', //主入口模块
    tableSearch: '../layui/lay/modules/tableSearch/tableSearch',
}).use(['index', 'table', 'laytpl', 'tableSearch'], function(){
    var $ = layui.$,
        form = layui.form,
        table = layui.table,
        tableSearch = layui.tableSearch;

    table.render({
        id: 'data-table',
        elem: '#data-table',
        url: 'holdAppraise/list',
        where: getData(),
        toolbar: '#data-table-toolbar',
        title: '主播评价',
        height: 'full-30',
        page: true,
        autoSort: false,    //自主排序
        limit: 50,
        cols: [[
            {field: 'userId', title: '主播id', width: 135, align: 'center'},
            {field: 'badNum', title: '差评数', width: 100, align: 'center', sort: true},
            {field: 'badRate', title: '差评率', width: 195, align: 'center', sort: true, templet: '#badRateTpl'},
            {field: 'goodNum', title: '好评数', width: 100, align: 'center', sort: true},
            {field: 'goodRate', title: '好评率', width: 195, align: 'center', sort: true, templet: '#goodRateTpl'},
            {field: 'appraiseNum', title: '总评价次数', width: 120, align: 'center', sort: true},
            {field: 'totalHoldNum', title: '总通话次数', width: 195, align: 'center', sort: true},
            {field: 'avgHoldTime', title: '平均通话时长', width: 195, align: 'center', sort: true},
            {field: 'remarks', title: '备注', align: 'center', templet:
                function (d) {
                    var remark = "";
                    if(d.remarks != null){
                        for(var i in d.remarks){
                            remark += d.remarks[i] + "<br>";
                        }
                        remark = remark.substring(0, remark.lastIndexOf("<br>"))
                    }
                    return remark;
                }
            },
            {field: 'op', title: '操作', width: 150, align: 'center', templet: '#data-table-bar'}
        ]],
        initSort: { //默认排序
            field: 'badNum',
            type: 'desc'
        },
        parseData: function(result){
            return {
                "code": result.code, //解析接口状态
                "msg": result.msg, //解析提示文本
                "count": result.data.total, //解析数据长度
                "data": result.data.datas //解析数据列表
            };
        },
        done: function (res, curr, count){
            //表格reload之后重新加载查询条件
            if($('#data-table').next().find('.layui-table-header').find('tr').length < 2){
                initSearch.reload();
            }
        }
    });

    //加载查询条件
    var initSearch = tableSearch.render({
        'elem': '#data-table',
        'searchs': [
            {field: 'userId', type: 'input'},
            {field: 'badRate', type: 'radius'},
            {field: 'goodRate', type: 'radius'},
            {field: 'totalHoldNum', type: 'radius'},
            {field: 'avgHoldTime', type: 'radius'}
        ],
        'searchBarData': [
            {field: 'time', type: 'date', format: 'datetime'}
        ],
        'done': function(res){
            // reloadData();
        }
    });

    //头工具栏事件
    table.on('toolbar(data-table)', function(obj){
        var checks = table.checkStatus(obj.config.id);
        var data = checks.data;
        switch(obj.event){
            case 'search':
                var data =  getData();
                table.reload('data-table', {
                    url: 'holdAppraise/list',
                    where: data,
                    page: {
                        curr: 1
                    }
                });
                break;
            case 'reset':
                tableSearch.resetData({});
                break;
        };
    });

    //监听行工具事件
    table.on('tool(data-table)', function(obj){
        var data = obj.data;
        if(obj.event === 'addRemark'){
            layer.open({
                type: 2,
                title: '新增用户备注',
                offset: '25%',
                content: 'toEditUserRemarkLog',
                area: ['500px', '400px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#userId').val(data.userId);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(res){
                        var field = res.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();
                        post('remarkLog/edit', field, false, function (resultData) {
                            var remarks = data.remarks;
                            if(field.type > 0){
                                remarks.push(field.content);
                            }
                            obj.update({
                                remarks: remarks,
                            });

                            layer.close(index); //关闭弹层
                            layer.close(load);
                            layer.msg("更新成功");
                        });
                    });

                    submit.trigger('click');
                }
            });
        }
    });

    //监听排序事件
    table.on('sort(data-table)', function(obj){
        var field = obj.field;  //当前排序的字段名
        var sort = obj.type;    //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

        var data = getData();
        data.field = field;
        data.sort = sort;

        table.reload('data-table', {
            initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。
            where: data,
            page: {
                curr: 1
            }
        });
    });

    form.on('select(selHoldNum)', function (data) {
        $("#holdNum").val(data.value);
    });

    /**
     * 获取查询数据
     * @returns {{host: jQuery, online: jQuery, keyword: (*|jQuery|Array|string|undefined), status: (*|jQuery|Array|string|undefined)}}
     */
    function getData() {
        return tableSearch.getData({});
    }
});